const { DataSystemDictDataModel } = require("../models/sys_dict_data");
const { DataSystemLogininforModel } = require("../models/sys_logininfor");
const { fail, CODE, success } = require("../utils/utils");
const xlsx = require("node-xlsx");

class SystemLogininfoController {
  /**
   * @description 删除登录信息
   * @param {Number} info_id
   */
  static async sysLogininfoDel (ctx, next) {
    const { info_id } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!info_id) {
        return (ctx.body = fail([], `info_id 获取失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemLogininforModel.delete({ op_user_id, info_id });
      return (ctx.body = success([], `登录信息删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 批量删除登录信息
   * @param {Number} ids
   */
  static async sysLogininfoDelByIds (ctx, next) {
    const { ids } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return (ctx.body = fail([], `删除失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemLogininforModel.deleteByIds({ op_user_id, ids });
      return (ctx.body = success([], `登录信息批量删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 登录信息分页列表
   * @param {String} login_name
   * @param {String} ipaddr
   * @param {String} status
   * @param {String} limit
   * @param {String} size
   */
  static async sysLogininfoList (ctx, next) {
    try {
      const { page_num, page_size, login_name, ipaddr, status } =
        ctx.request.query;
      let limit = Number(page_num) || 1;
      let size = Number(page_size) || 10;
      const { result, count } = await DataSystemLogininforModel.list({
        limit,
        size,
        login_name,
        ipaddr,
        status,
      });
      return (ctx.body = success(
        { result, total: count[0].count },
        `获取登录信息数据成功`,
        CODE.SUCCESS
      ));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 导出数据
   */
  static async sysLogininfoExport (ctx, next) {
    try {
      const { login_name, ipaddr, status } = ctx.request.body;
      const { result } = await DataSystemLogininforModel.findList({
        login_name,
        ipaddr,
        status,
      });
      const sys_common_status_result =
        await DataSystemDictDataModel.findBySystemdDictType({
          dict_type: "sys_common_status",
        });
      let data = result.map((item) => {
        let current_staus = sys_common_status_result.find(
          (snd) => snd.dict_value === item.status
        );
        item.status = current_staus ? current_staus.dict_label : item.status;
        return item;
      });
      const excelData = [
        [
          "登录账号",
          "登录IP",
          "登录地址",
          "浏览器",
          "操作系统",
          "登录状态",
          "操作信息",
          "创建时间",
        ],
        ...data.map((item) => [
          item.login_name,
          item.ipaddr,
          item.login_location,
          item.browser,
          item.os,
          item.status,
          item.msg,
          item.login_time,
        ]),
      ];
      const buffer = xlsx.build([{ name: "Sheet1", data: excelData }]);

      // 设置返回的http header信息，告诉浏览器该文件是一个excel文件
      ctx.set(
        "Content-Type",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      );
      ctx.set(
        "Content-Disposition",
        "attachment; filename=" + encodeURIComponent("登录信息数据.xlsx")
      );

      // 将生成的excel文件发送给客户端
      ctx.body = buffer;
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 清除登录信息
   * @param {Number} ids
   */
  static async sysLogininfoClean (ctx, next) {
    const { user_id: op_user_id } = ctx.state.user;
    try {
      await DataSystemLogininforModel.clean({ op_user_id });
      return (ctx.body = success([], `删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
}

module.exports = {
  SystemLogininfoController,
};
